package com.Rest2Go;

import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.Rest2Go.Utils.Utils;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionEvents;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionStore;

public class FacebookLoginHelper
{

	private static FacebookLoginHelper	_instance;
	private Facebook					mFacebook;
	private Activity					mActivity;
	private Handler						mHandler;
	private static String				mName;
	private static String				mEmail;
	private static String				mFbId;
	private static int					mMoveEatUID;

	public FacebookLoginHelper(Activity act)
	{
		mActivity = act;
		_instance = this;
	}
	public void facebookLogout(){
		
//		SessionStore.clear(mActivity);
		SessionEvents.onLogoutBegin();
        AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFacebook);
        asyncRunner.logout(mActivity, new LogoutRequestListener());
		Editor edit = PreferenceManager.getDefaultSharedPreferences(mActivity).edit();
		edit.putInt(Consts.Extras.ME_UID, -1);
		edit.commit();
		Toast.makeText(mActivity, "You are now logged from Facebook", Toast.LENGTH_LONG).show();
	}
	public void facebookSignIn()
	{
		mHandler = new Handler();
		mFacebook = new Facebook(Consts.FACEBOOK_APP_ID);
		SessionStore.restore(mFacebook, mActivity);
		SessionEvents.addAuthListener(new AuthListener()
		{

			@Override
			public void onAuthSucceed()
			{
				SessionStore.save(mFacebook, mActivity);
				Toast.makeText(mActivity, "You have successfuly signed in!", Toast.LENGTH_LONG).show();

			}

			@Override
			public void onAuthFail(String error)
			{
				AlertDialog.Builder builder = new Builder(mActivity);
				builder.setIcon(android.R.drawable.ic_dialog_alert);
				builder.setMessage("There was a problem signning in using facebook: " + error);
				builder.setPositiveButton("Back", new OnClickListener()
				{

					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
					}
				});
				AlertDialog alert = builder.create();
				alert.show();

			}
		});

		mFacebook.authorize(mActivity, new String[] { "user_about_me", "email" }, new LoginDialogListener());

		// Bundle args = new Bundle();
		// args.putString("fields", "birthday,name,picture");

	}

	private class LogoutRequestListener extends BaseRequestListener
	{
		public void onComplete(String response, final Object state)
		{
			// callback should be run in the original thread,
			// not the background thread
			mHandler.post(new Runnable()
			{
				public void run()
				{
					SessionEvents.onLogoutFinish();
				}
			});
		}
	}

	private final class LoginDialogListener implements DialogListener
	{

		public void onComplete(Bundle values)
		{
			SessionEvents.onLoginSuccess();

			new AsyncFacebookRunner(mFacebook).request("me", new BaseRequestListener()
			{

				@Override
				public void onComplete(String response, Object state)
				{
					if (response != null)
					{
						try
						{
							Utils.log(response);
							JSONObject user = new JSONObject(response);
							mName = user.optString("name");
							mFbId = user.optString("id");
							mEmail = user.optString("email");
							
							new AsyncTask<Void, Void, String>()
							{
								@Override
								protected String doInBackground(Void... params)
								{
									return (registerUserToMoveEatDB());
								}

								@Override
								protected void onPostExecute(String res)
								{
									if (res != null)
									{
										try
										{
											JSONObject obj = new JSONObject(res);
											mMoveEatUID = Integer.parseInt(obj.optJSONArray("USER").optJSONObject(0).optString("ID"));
											Editor edit = PreferenceManager.getDefaultSharedPreferences(mActivity).edit();
											edit.putInt(Consts.Extras.ME_UID, mMoveEatUID);
											edit.commit();
										}
										catch (JSONException e)
										{
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								}

							}.execute();

						}
						catch (JSONException ex)
						{
							Utils.log("Problem creating JSONObject" + ex.getMessage());
						}

					}
				}
			});

			
		}

		public void onFacebookError(FacebookError error)
		{
			SessionEvents.onLoginError(error.getMessage());
		}

		public void onError(DialogError error)
		{
			SessionEvents.onLoginError(error.getMessage());
		}

		public void onCancel()
		{
			SessionEvents.onLoginError("Action Canceled");
		}
	}

	public static FacebookLoginHelper getInstance()
	{
		if (_instance==null){
			
		}
		return _instance;
	}

	public String registerUserToMoveEatDB()
	{
		if (mFbId != null && mName != null && mEmail != null)
		{
			
			String answer = Utils.preformRequest(Utils.BASE_URL + "register.php?mFbId=" + mFbId + "&name=" + URLEncoder.encode(mName) + "&email=" + URLEncoder.encode(mEmail));
			Utils.log(answer);
			return answer;
		}
		return null;

	}

	public int getMoveEatUID()
	{
		return mMoveEatUID;
	}

}
